﻿using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Orchard.Localization;
using Orchard.Environment.Extensions;

namespace FruitCake.SupportLibrary.Extensions
{
    [OrchardFeature("FruitCake.SupportLibrary.Extensions")]
    public static class FruitHtmlExtensions
    {
        public static IHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, LocalizedString labelText)
        {
            return MvcHtmlString.Create(htmlHelper.CheckBoxFor<TModel>(expression).ToString() + htmlHelper.LabelFor(expression, labelText, "forcheckbox"));
        }

        public static IHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, LocalizedString labelText, string cssClass)
        {
            return LabelFor(html, expression, labelText.ToString(), cssClass);
        }

        public static IHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, string cssClass)
        {
            if (String.IsNullOrEmpty(labelText))
            {
                return MvcHtmlString.Empty;
            }
            var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            var tag = new TagBuilder("label");
            tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
            if (!string.IsNullOrWhiteSpace(cssClass))
                tag.Attributes.Add("class", cssClass);            
            tag.SetInnerText(labelText);
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }

        public static IHtmlString HintText(this HtmlHelper html, LocalizedString text)
        {
            return HintText(html, text.ToString());
        }

        public static IHtmlString HintText(this HtmlHelper html, string text)
        {
            var tag = new TagBuilder("span");
            tag.Attributes.Add("class", "hint");
            tag.SetInnerText(text);
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    }
}